#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"
namespace socket_ns
{
    class Socket;
    using socket_sprt = std::shared_ptr<Socket>;

    int gbacklog = 16;

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR,
        USAGE_ERROR,
        ACCEPT_ERROR,
        CONNECT_ERROR
    };

    // 模板方法模式
    class Socket
    {
    public:
        virtual void CreateSockOrDie() = 0;
        virtual void BindSockOrDie(InetAddr &) = 0; // 参数为服务器绑定的套接字地址
        virtual void ListenSockOrDie() = 0;
        virtual void SetSocketAddrReuse() = 0;
        virtual socket_sprt Accepter(InetAddr *) = 0; // Accepter返回一个用于IO的套接字地址；参数是申请通信的客户端套接字地址
        virtual bool Connector(InetAddr &peer) = 0;   // 参数是服务器绑定的套接字地址
        virtual int Recv(std::string*) = 0;
        virtual int Send(const std::string&) = 0;
        virtual int SockFd() = 0;
        virtual void Close() = 0;

    public:
        void BuildListenSocket(InetAddr &addr)
        {
            CreateSockOrDie();
            SetSocketAddrReuse();
            BindSockOrDie(addr);
            ListenSockOrDie();
        }

        bool BuildClientSocket(InetAddr &addr)
        {
            CreateSockOrDie();
            return Connector(addr);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = -1) : _sockfd(sockfd)
        {
        }
        int SockFd() override
        {
            return _sockfd;
        }
        void Close() override
        {
            if (_sockfd > -1)
                ::close(_sockfd);
        }
        void SetSocketAddrReuse()
        {
            int opt = 1;
            ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        }
        void CreateSockOrDie() override
        {
            // 1. 创建套接字
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket error...");
                exit(SOCKET_ERROR);
            }
            LOG(DEBUG, "socket create success, sockfd is: %d", _sockfd);
        }

        // 服务器绑定一个套接字地址
        void BindSockOrDie(InetAddr &addr) override
        {
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = bind(_sockfd, (sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error...");
                exit(BIND_ERROR);
            }
            LOG(DEBUG, "bind success, sockfd is : %d", _sockfd);
        }

        void ListenSockOrDie() override
        {
            int n = ::listen(_sockfd, gbacklog); // 将_fd设置为监听状态
            if (n < 0)
            {
                LOG(FATAL, "listen eroor...");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "listen success, sockfd is : %d", _sockfd);
        }

        socket_sprt Accepter(InetAddr *addr) override // 返回用于网络IO的套接字
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len); // accept会从监听套接字中接受链接，并将申请链接的client信息返回
                                                                            // 同时返回一个文件描述符用于与client通信
            if (sockfd < 0)
            {
                // 获取链接失败是一般问题，不严重
                LOG(WARNING, "accept error");
                exit(ACCEPT_ERROR);
            }
            *addr = peer;
            socket_sprt ptr = std::make_shared<TcpSocket>(sockfd); // sockfd用于网络通信，后续通过ptr->Send() ptr->Recv接受发送数据
            return ptr;                                            // ptr->Send() ptr->Recv()
        }

        bool Connector(InetAddr &peer) override
        {
            // 构建目标主机的信息
            struct sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peer.Port());
            server.sin_addr.s_addr = inet_addr(peer.Ip().c_str());

            // 申请连接
            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "connect error..." << std::endl;
                return false;
            }
            return true;
        }
        int Send(const std::string& in)
        {
            int n = ::send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }
        int Recv(std::string* out)
        {
            char buffer[1024];
            int n = ::recv(_sockfd, buffer, sizeof(buffer), 0); // bug
            // 读取数据成功
            if (n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }

    private:
        int _sockfd;
    };
}
